#!/usr/bin/env python
# encoding=utf-8

__author__ = 'Bunyk T.'
__version__ = '0.1'

import codecs
import sys

import curses

import locale
locale.setlocale(locale.LC_ALL, '')
coding = locale.getpreferredencoding()

curses.KEY_ESC = 27
curses.KEY_ENTER = ord('\n')

class Typewriter(object):
    def __init__(self, file_name, screen):
        self.row = u''
        self.file_name = file_name
        self.screen = screen
        self.buf = ''
        try:
            with codecs.open(self.file_name, 'r', coding) as f:
                for line in f:
                    self.screen.addstr(line.encode(coding))
        except IOError:
            self.screen.addstr('Typing to new file %s' % file_name)
            

    def add_char(self, key):
        try:
            key = chr(key)
        except ValueError:
            return
        try: # read Unicode byte by byte
            self.row += unicode(self.buf + key, coding)
            self.screen.addstr(self.row[-1].encode(coding))
            self.buf = ''
        except UnicodeDecodeError: # partial character
            self.buf += key

    def make_newline(self):
        with codecs.open(self.file_name, 'a', coding) as f:
            f.write(self.row + u'\n')
        self.screen.addch('\n')
        self.row = u''

def main(screen):
    if len(sys.argv) < 2:
        sys.exit('You should pass filename as first parameter.')
    screen.scrollok(True)
    tt = Typewriter(sys.argv[1], screen)
    screen.addstr("                           * * *                        \n")
    screen.addstr("                                                        \n")
    screen.addstr("________________________________________________________\n")
    screen.addstr("Typewriter simulator. There is no backspace.            \n")
    screen.addstr("Only Enter to make a new line. And Esc to exit.         \n")
    screen.addstr("Above you see tail of the file you typing to.           \n")
    screen.addstr("So just let's go to work!                               \n")
    screen.addstr("________________________________________________________\n")
    screen.addstr("                                                        \n")
    screen.addstr("                           * * *                        \n")
    screen.refresh()
    while True:
        key = screen.getch()
        if key == curses.KEY_ESC:
            tt.make_newline()
            break
        elif key == curses.KEY_ENTER:
            tt.make_newline()
        elif key in (curses.KEY_BACKSPACE, curses.KEY_LEFT):
            pass
        else:
            tt.add_char(key)

if __name__ == '__main__': 
    curses.wrapper(main)
